// ActionScript file
import Modules.NavigationInfo;
import Modules.PostLogin;
import Modules.Windows.CMDWindow;

import com.desidea.common.CommonClass;
import com.desidea.common.MenuConstants;
import com.desidea.components.grid.SuperGridEvent;
import com.desidea.components.grid.button.SuperGridButton;
import com.desidea.utils.DirtyChecker;
import com.desidea.utils.IDirtyChecker;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import flash.events.MouseEvent;

import mx.controls.Alert;
import mx.controls.LinkButton;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.core.Application;
import mx.events.ValidationResultEvent;
import mx.rpc.events.FaultEvent;
import mx.utils.StringUtil;


private var _btnEditCancel:LinkButton;
private var _btnAddContact:LinkButton;
private var _btnAddActivity:LinkButton;
private var _btnAddTask:LinkButton;
private var _btnAddOpportunity:LinkButton;

private var _key:String = "";
private var _mode:String = "view";//Constants.MODE_ADD;
private var _modeSet:Boolean = false;
private var _creationCompleted:Boolean = false;
private var acctdetails:XML;

public function get mode():String{
	return _mode;
}

public function set mode(value:String):void{
	this._mode = value;
	this._modeSet = true;
	
//	setScreenMode();
//	this.loadData();
}

public function get key():String{
	return _key;
}

public function set key(value:String):void{
	this._key = value;
}

private function init():void{
	this.txtNotes.linkTextInput.visible = false;
	this.txtNotes._RichTextEditor_VRule2.visible = false;
}

private function setScreenMode():void{
	if(!_creationCompleted) return;
	
	if(this.mode == SuperGridButton.MODE_VIEW || mode == SuperGridButton.MODE_VIEWICON){
		frmAccountInfo.enabled = false;
		rtVBox.percentWidth = 50;
		rtVBox.visible = true;
		btnSubmit.enabled = false;
		this.lblTitle.text = "View Account Details";
	}else if(this.mode == SuperGridButton.MODE_EDIT){		//MODE_EDIT = create new
		frmAccountInfo.enabled = true;
		btnSubmit.enabled = true;
		_btnEditCancel.enabled = false;
		
		cmbParentAccount.enabled = true;
		cmbAccountOwner.enabled = false;
		cmbAccountOwner.selectedItem = (acctdetails.USERS.entry.(@id == CommonClass.UserID.toString())[0]) as XML;
		cmbContacts.enabled = false;
		this.lblTitle.text = "New Account";
	}
}

private function windowCreated():void{
	_btnEditCancel = new LinkButton();
	_btnEditCancel.label = "Edit";	
	_btnEditCancel.height = this.pnlAccountInfo.ToolBox.height - 2;
	_btnEditCancel.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('editdetails'); });
	this.pnlAccountInfo.ToolBox.addChild(_btnEditCancel);

	_btnAddContact = new LinkButton();
	_btnAddContact.label = "New Contact";
	_btnAddContact.height = this.pnlContacts.ToolBox.height - 2;
	_btnAddContact.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('newcontact'); });
	this.pnlContacts.ToolBox.addChild(_btnAddContact);

	_btnAddActivity = new LinkButton();
	_btnAddActivity.label = "New Activity";
	_btnAddActivity.height = this.pnlActivities.ToolBox.height - 2;
	_btnAddActivity.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('newactivity'); });
	this.pnlActivities.ToolBox.addChild(_btnAddActivity);

	_btnAddTask = new LinkButton();
	_btnAddTask.label = "New Task";
	_btnAddTask.height = this.pnlTasks.ToolBox.height - 2;
	_btnAddTask.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('newtask'); });
	this.pnlTasks.ToolBox.addChild(_btnAddTask);

	_btnAddOpportunity = new LinkButton();
	_btnAddOpportunity.label = "New Opportunity";
	_btnAddOpportunity.height = this.pnlOpportunities.ToolBox.height - 2;
	_btnAddOpportunity.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick("newopportunity"); });
	this.pnlOpportunities.ToolBox.addChild(_btnAddOpportunity);


	pnlContacts.height = dgContacts.height;
	
//	if(pnlActivities.open){
		pnlActivities.height = dgActivities.height
//	}

//	if(pnlTasks.open){
		pnlTasks.height = dgTasks.height
//	}
	
//	if(pnlOpportunities.open){
		pnlOpportunities.height = dgOpps.height
//	}
	
	dgContacts.addEventListener(SuperGridEvent.CLICKED, contactsGridButtonColumnClicked);
	dgActivities.addEventListener(SuperGridEvent.CLICKED, activitiesGridButtonColumnClicked);
	dgTasks.addEventListener(SuperGridEvent.CLICKED, tasksGridButtonColumnClicked);
	dgOpps.addEventListener(SuperGridEvent.CLICKED, oppsGridButtonColumnClicked);

	this._creationCompleted = true;
	this.loadData();
}

private function loadData():void{
	if( DirtyChecker.getInstance().isDirty){
		if (DirtyChecker.getInstance().sourceContainer is IDirtyChecker){
			(DirtyChecker.getInstance().sourceContainer as IDirtyChecker).promptToSave();
		}else{
			Alert.show("Save & Proceed");
		}
		return;
	}else{
		DirtyChecker.getInstance().resetDirtyChecker();
	}
	
	
	var params:String = "OPERATION=ACCOUNT_GETDETAILS" +
						"&PKID=" + escape(StringUtil.trim(this.key));
//						"&USERID=1";
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForAccountDetails);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForAccountDetails(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	acctdetails = XML(event.result);
//	Alert.show(acctdetails.toString());
	if(acctdetails.RESPONSE.RESULT == "E"){
		Alert.show(acctdetails.RESPONSE.MESSAGE);
	}else if(acctdetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(acctdetails);
		setScreenMode();
		this.loadAccountContacts();
		this.loadAccountActivities();
		this.loadAccountTasks();
		this.loadAccountOpps();
	}
}

private function partnerServiceFaultHandler(event:FaultEvent):void{
//	BusySpinner.getInstance().stop();
	Alert.show(event.fault.toString());
}

private function setDataOnControls(response:XML):void{
	cmbParentAccount.dataProvider = new XML(response.PARENTACCOUNTS).entry as XMLList;
	cmbParentAccount.selectedItem = (response.PARENTACCOUNTS.entry.(@id == response.RELATIONS.RELATION.(@type == "PARENT_ACCOUNT"))[0]) as XML
	cmbParentAccount.selectedIndex = (cmbParentAccount.selectedIndex <0)?0:cmbParentAccount.selectedIndex;
	
	cmbAccountOwner.dataProvider = new XML(response.USERS).entry as XMLList;
	cmbAccountOwner.selectedIndex = 0;
	cmbAccountOwner.selectedItem = (response.USERS.entry.(@id == response.RELATIONS.RELATION.(@type == "OWNER"))[0]) as XML
	
	cmbContacts.dataProvider = new XML(response.CONTACTS).entry as XMLList;
	cmbContacts.selectedIndex = 0;
	cmbContacts.selectedItem = (response.CONTACTS.entry.(@id == response.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML ///check PRIMARY_CONTACT
	
	cmbAccountType.dataProvider = new XML(response.ACCOUNTTYPES).entry as XMLList;
	cmbAccountType.selectedItem = (response.ACCOUNTTYPES.entry.(@id == response.ACCOUNTTYPEID)[0]) as XML
	cmbAccountType.selectedIndex = (cmbAccountType.selectedIndex<0)?0:cmbAccountType.selectedIndex;
	
	cmbState.dataProvider = new XML(response.STATES).entry as XMLList;
	cmbState.selectedIndex = 0;
	cmbState.selectedItem = (response.STATES.entry.(@id == response.STATE)[0]) as XML

	cmbVertical.dataProvider = new XML(response.VERTICALS).entry as XMLList;
	cmbVertical.selectedIndex = 0;
	cmbVertical.selectedItem = (response.VERTICALS.entry.(@id == response.VERTICALID)[0]) as XML
		
	cmbResellerName.dataProvider = new XML(response.RESELLERACCOUNTS).entry as XMLList;
	cmbResellerName.selectedIndex = 0;
	cmbResellerName.selectedItem = (response.RESELLERACCOUNTS.entry.(@id == response.RELATIONS.RELATION.(@type == "RESELLER"))[0]) as XML ///check PRIMARY_CONTACT
	
	cmbReferralSource.dataProvider = new XML(response.REFSOURCES).entry as XMLList;
	cmbReferralSource.selectedIndex = 0;
	cmbReferralSource.selectedItem = (response.REFSOURCES.entry.(@id == response.REFERRALSOURCEID)[0]) as XML
	
	CommonClass.setDataOnComponents(this.txtAccountName, response);
	CommonClass.setDataOnComponents(this.txtNoOfLocations, response);
	CommonClass.setDataOnComponents(this.txtAddress, response);
	CommonClass.setDataOnComponents(this.txtCity, response);
	CommonClass.setDataOnComponents(this.txtZipCode, response);
	CommonClass.setDataOnComponents(this.txtTelephoneNo, response);
	CommonClass.setDataOnComponents(this.txtFaxNo, response);
	CommonClass.setDataOnComponents(this.txtWebsite, response);
	CommonClass.setDataOnComponents(this.txtNotes, response);
	CommonClass.setDataOnComponents(this.chkActive, response);
}

private function getPostData():String{
	var postData:String = new String();
	postData += "ACCOUNTNO=" + (acctdetails.ACCOUNTNO.toString())			+ "&";
	postData += "ACCOUNTGUID=" + (acctdetails.ACCOUNTGUID.toString())		+ "&";
	postData += (CommonClass.preparePostString(this.txtAccountName))			+ "&";
	postData += (CommonClass.preparePostString(this.txtNoOfLocations))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbAccountType))			+ "&";
	postData += (CommonClass.preparePostString(this.txtAddress))				+ "&";
	postData += (CommonClass.preparePostString(this.txtCity))					+ "&";
	postData += (CommonClass.preparePostString(this.cmbState))					+ "&";
	postData += (CommonClass.preparePostString(this.txtZipCode))				+ "&";
	postData += (CommonClass.preparePostString(this.txtTelephoneNo))			+ "&";
	postData += (CommonClass.preparePostString(this.txtFaxNo))					+ "&";
	postData += (CommonClass.preparePostString(this.txtWebsite))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbVertical))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbReferralSource))			+ "&";
	postData += "NOTEID=" + (acctdetails.NOTEID.toString())						+ "&";
	postData += (CommonClass.preparePostString(this.txtNotes))					+ "&";
	postData += (CommonClass.preparePostString(this.chkActive))					+ "&";
	postData += "USERID=" + (CommonClass.UserID)								+ "&";
	postData += "ADDRESSNO=" + (acctdetails.ADDRESSNO.toString())				+ "&";
	postData += "ADDRESSGUID=" + (acctdetails.ADDRESSGUID.toString())			+ "&";
	postData += "COMMUNICATIONID=" + (acctdetails.COMMUNICATIONID.toString())	+ "&";
	postData += (CommonClass.preparePostString(this.cmbParentAccount))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbAccountOwner))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbContacts))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbResellerName));
	return postData;	
}

private function saveData(action:String, data:String=""):void{
	var params:String = "OPERATION=ACCOUNT_UPDATEDETAILS" +
						(data.length>0?"&":"") +data;
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateAccountDetails);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.parentApplication);
}


private function callForUpdateAccountDetails(event:ProcessServiceRequestResultEvent):void{
	
	var response:XML = XML(event.result);
//	BusySpinner.getInstance().stop();
	
	if(response.RESPONSE.RESULT == "S"){
		DirtyChecker.getInstance().resetDirtyChecker();
		handleCancelClick();
	}else{
		Alert.show( String(response.toString()) );	
	}	
	
}


private function onClick(mode:String):void{
	switch(mode){
		case "editdetails":
//			Alert.show("Edit Details");
			frmAccountInfo.enabled = true;
			btnSubmit.enabled = true;
			cmbParentAccount.enabled = true;
			cmbAccountOwner.enabled = false;
			_btnEditCancel.enabled = false;
			this.lblTitle.text = "Edit Account Details";
			break;
		case "newcontact":
			var conNI:NavigationInfo = new NavigationInfo(this.key, MenuConstants.CMD, MenuConstants.MY_CONTACTS,"");
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(conNI);
			break;		
		case "newactivity":
			var actNI:NavigationInfo = new NavigationInfo(this.key, MenuConstants.CMD, MenuConstants.MY_ACTIVITIES,"");
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(actNI);
			break;		
		case "newtask":
			var taskNI:NavigationInfo = new NavigationInfo(this.key, MenuConstants.CMD, MenuConstants.MY_TASKS,"");
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(taskNI);
			break;		
		case "newopportunity":
			var oppNI:NavigationInfo = new NavigationInfo(this.key, MenuConstants.CMD, MenuConstants.MY_OPPORTUNITIES,"");
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(oppNI);
			break;		
	}
}

private function buttonClick(eventType:String):void{
	switch(eventType){
		case "save":
			handleSubmitClick();
			break;
		case "cancel":
			handleCancelClick();
			break;
		default:
			Alert.show( "Yet to Implement : " + eventType);
	}
}

private function handleCancelClick():void{
	(this.parentDocument as CMDWindow).NavInfo = null;
	(this.parentDocument as CMDWindow).loadModule();
}

private function handleSubmitClick():void{
	if(validate()){
		saveData("", getPostData());
	}else{
		Alert.show("Please provide missing/incorrect details before saving","Save");
	}
}



// Load data for Account Contacts Grid
private function loadAccountContacts():void{
	//Dirty Checker needed  ??
	
	
	var params:String = "OPERATION=ACCOUNT_CONTACTS" +
						"&accountGUID=" + escape(acctdetails.ACCOUNTGUID) +
						"&USERID=" + CommonClass.UserID +
						"&ISACTIVE=" + escape(acctdetails.ISACTIVE);
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForAccountContacts);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForAccountContacts(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	var acctcontacts:XML = XML(event.result);
//	Alert.show(acctcontacts.toString());
	if(acctcontacts.RESPONSE.RESULT == "E"){
		Alert.show(acctcontacts.RESPONSE.MESSAGE);
	}else if(acctcontacts.RESPONSE.RESULT == 'S'){
		dgContacts.dataProvider = acctcontacts;
	}
	setContactsGridColumnWidths(dgContacts);
}

private function setContactsGridColumnWidths(grid:SuperGrid):void{
	setColumnWidth(grid, 1, 110);
	setColumnWidth(grid, 2, 75);
	setColumnWidth(grid, 3, 90);
}

// Load data for Account Activities Grid
private function loadAccountActivities():void{
	//Dirty Checker needed  ??
	
	
	var params:String = "OPERATION=ACCOUNT_ACTIVITIES" +
						"&accountGUID=" + escape(acctdetails.ACCOUNTGUID) +
						"&USERID=" + CommonClass.UserID;
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForAccountActivities);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForAccountActivities(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	var acctActivities:XML = XML(event.result);
//	Alert.show(acctActivities.toString());
	if(acctActivities.RESPONSE.RESULT == "E"){
		Alert.show(acctActivities.RESPONSE.MESSAGE);
	}else if(acctActivities.RESPONSE.RESULT == 'S'){
		dgActivities.dataProvider = acctActivities;
	}
	setActivitiesGridColumnWidths(dgActivities);
}
private function setActivitiesGridColumnWidths(grid:SuperGrid):void{
	setColumnWidth(grid, 1, 100);
	setColumnWidth(grid, 2, 90);
	setColumnWidth(grid, 3, 60);
	setColumnWidth(grid, 4, 100);
}

// Load data for Account Tasks Grid
private function loadAccountTasks():void{
	//Dirty Checker needed  ??
	
	
	var params:String = "OPERATION=ACCOUNT_TASKS" +
						"&accountGUID=" + escape(acctdetails.ACCOUNTGUID) +
						"&USERID=" + CommonClass.UserID;
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForAccountTasks);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForAccountTasks(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	var acctTasks:XML = XML(event.result);
//	Alert.show(acctTasks.toString());
	if(acctTasks.RESPONSE.RESULT == "E"){
		Alert.show(acctTasks.RESPONSE.MESSAGE);
	}else if(acctTasks.RESPONSE.RESULT == 'S'){
		dgTasks.dataProvider = acctTasks;
	}
	setTasksGridColumnWidths(dgTasks);
}

private function setTasksGridColumnWidths(grid:SuperGrid):void{
	setColumnWidth(grid, 1, 110);
	setColumnWidth(grid, 2, 75);
	setColumnWidth(grid, 3, 80);
	setColumnWidth(grid, 4, 50);
}



// Load data for Account Opportunities Grid
private function loadAccountOpps():void{
	//Dirty Checker needed  ??
	
	
	var params:String = "OPERATION=ACCOUNT_OPPORTUNITIES" +
						"&accountGUID=" + escape(acctdetails.ACCOUNTGUID) +
						"&USERID=" + CommonClass.UserID;
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForAccountOpps);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForAccountOpps(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	var acctOpps:XML = XML(event.result);
//	Alert.show(acctOpps.toString());
	if(acctOpps.RESPONSE.RESULT == "E"){
		Alert.show(acctOpps.RESPONSE.MESSAGE);
	}else if(acctOpps.RESPONSE.RESULT == 'S'){
		dgOpps.dataProvider = acctOpps;
	}
//	setOppsGridColumnWidths(dgOpps);
}

private function setOppsGridColumnWidths(grid:SuperGrid):void{
	setColumnWidth(grid, 1, 110);
	setColumnWidth(grid, 2, 80);
}


private function contactsGridButtonColumnClicked(event:SuperGridEvent):void{
	handleGridButtonClick(event, "contacts");
}

private function activitiesGridButtonColumnClicked(event:SuperGridEvent):void{
	handleGridButtonClick(event, "activities");
}

private function tasksGridButtonColumnClicked(event:SuperGridEvent):void{
	handleGridButtonClick(event, "tasks");
}

private function oppsGridButtonColumnClicked(event:SuperGridEvent):void{
	handleGridButtonClick(event, "opps");
}

private function handleGridButtonClick(event:SuperGridEvent, moduleCode:String = null):void{
	var mode:String =  String(event.data.linkId).toLowerCase();
	
	switch(moduleCode){
		case "contacts":
			var conNI:NavigationInfo = new NavigationInfo("",MenuConstants.CMD, MenuConstants.MY_CONTACTS, event.data.data["key"].toString());
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(conNI);
			break;
		case "activities":
			var actNI:NavigationInfo = new NavigationInfo("",MenuConstants.CMD, MenuConstants.MY_ACTIVITIES, event.data.data["key"].toString());
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(actNI);
			break;
		case "tasks":
			var tasksNI:NavigationInfo = new NavigationInfo("",MenuConstants.CMD, MenuConstants.MY_TASKS, event.data.data["key"].toString());
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(tasksNI);
			break;
		case "opps":
			var oppsNI:NavigationInfo = new NavigationInfo("",MenuConstants.CMD, MenuConstants.MY_OPPORTUNITIES, event.data.data["key"].toString());
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(oppsNI);
			break;
	}
	
}

private function setColumnWidth(grid:SuperGrid, colIndex:int, colWidth:int, alignment:String = "left"):void{
	if(grid.GridComponent.columnCount > colIndex)	
		grid.GridComponent.columns[colIndex].width = colWidth;
		
		var col:DataGridColumn = grid.GridComponent.columns[colIndex];
		col.setStyle("textAlign", alignment);
}

private function validate():Boolean {
	return 	( nameV.validate().type == ValidationResultEvent.VALID) &&
			( locationV.validate().type == ValidationResultEvent.VALID) &&
			( accTypeV.validate().type == ValidationResultEvent.VALID) &&
			( addressV.validate().type == ValidationResultEvent.VALID) &&
			( cityV.validate().type == ValidationResultEvent.VALID) &&
			( stateV.validate().type == ValidationResultEvent.VALID) &&
			( zipV.validate().type == ValidationResultEvent.VALID) &&
			( phoneV.validate().type == ValidationResultEvent.VALID) &&
			( faxV.validate().type == ValidationResultEvent.VALID) &&
			( verticalV.validate().type == ValidationResultEvent.VALID) &&
			( refSrcV.validate().type == ValidationResultEvent.VALID);
}